<template>
  <div style="width: 100%">

    <el-form :inline="true" :model="queryParams" size="small" label-width="70px" class="filter-form-inline">
      <el-row :gutter="40">

        <el-col v-if="screenData" :span="6">
          <el-form-item label="统计方式">
            <el-select v-model="queryParams[screenData.name]" style="width: 100%" placeholder="统计方式"
              @change="handlQueryParams">
              <el-option v-for="item in screenData.options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col v-if="isCycle" :span="6">
          <el-form-item label="统计周期" style="width: 100%">
            <el-select v-model="queryParams.cycle" style="width: 100%" placeholder="统计周期">
              <el-option v-for="item in cycleData" :key="item.id" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="时间范围" style="width: 100%">
            <dateTime ref="dateTimeRef" :state="queryParams.cycle" @dateTime="dateTime" />
          </el-form-item>
        </el-col>

        <template v-if="visible">
          <el-col :span="6">
            <el-form-item label="筛选" style="width: 100%">
              <el-select v-model="queryParams.charge" clearable style="width: 100%" placeholder="请选择"
                @change="handlQueryParams">
                <!--              <el-option label="全部订单" value="0"/>-->
                <el-option label="我负责的订单" value="1" />
                <el-option label="我下级负责的" value="2" />
                <el-option label="我部门负责的" value="3" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="产品线" style="width: 100%">
              <el-select v-model="queryParams.productLine" clearable style="width: 100%" placeholder="请选择产品线"
                @change="handlQueryParams">
                <el-option v-for="item in listData" :key="item.id" :label="item.productLineName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="产品" style="width: 100%">
              <el-select v-model="queryParams.productId" filterable remote reserve-keyword placeholder="请输入产品"
                :remote-method="handlProductData" style="width: 100%" @change="handlQueryParams">
                <el-option v-for="item in productList" :key="item.id" :label="item.productPopularName"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="配送商" style="width: 100%">
              <el-select v-model="queryParams.distributeId" filterable remote reserve-keyword placeholder="请输入配送商"
                style="width: 100%" :remote-method="handlDistributeData" @change="handlQueryParams">
                <el-option v-for="item in distributeList" :key="item.id" :label="item.distributeName"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col
            v-if="type == 'timeView' || type == 'productView' || type == 'positionView' || type == 'clientView' || type == 'departmentView'"
            :span="6">
            <el-form-item label="部门人员" style="width: 100%">
              <el-cascader ref="cascader" v-model="queryParams.dep" :popper-append-to-body="false" :options="depOptions"
                :props="{expandTrigger: 'hover', checkStrictly: true ,label: 'deptName',value: 'id'}"
                placeholder="请选择部门人员" @change="depChange" />
            </el-form-item>
          </el-col>

          <el-col
            v-if="type == 'timeView' || type == 'productView' || type == 'positionView' || type == 'departmentView'"
            :span="6">
            <el-form-item label="客户" style="width: 100%">
              <el-cascader :options="clientOptions" :popper-append-to-body="false" :props="propsOption"
                placeholder="请选择客户" @change="clientChange" />
            </el-form-item>
          </el-col>

        </template>

        <el-col :span="3">
          <el-form-item style="width: 100%">
            <more-search-btn v-model:is-more="visible" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item style="width: 100%">
            <el-button class="border-btn" @click="handlReset">重置</el-button>
            <el-button type="primary" class="main-btn" @click="handlQueryParams">搜索</el-button>
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>

  </div>
</template>

<script>
import {defineAsyncComponent, getCurrentInstance, inject, onMounted, reactive, ref, toRefs, watch,} from "vue";
import {crmStore} from "@CRM/store";
import {useRoute} from "vue-router";

export default {
  name: "Form",
  components: {
    dateTime: defineAsyncComponent(() => import("./dateTime.vue")),
  },
  props: {
    isCycle: {
      type: Boolean,
      default: true,
    },
    screenData: {
      type: Object,
      default: null,
    },
    type: {
      type: String,
      default: "",
    },
  },
  setup(props, context) {
    const route = useRoute();
    const currentInstance = getCurrentInstance();
    const api = inject("api");
    const propsOption = ref({
      lazy: true,
      lazyLoad(node, resolve) {
        const { value } = node;
        console.log(node);
        if (value == 1) {
          api.signedAgent
            .AGENT_OPENED_ACCOUNT_LIST({ page: 1, pageSize: 1000 })
            .then((res) => {
              if (!res.code && res.data) {
                const list = [];
                res.data.list.forEach((item) => {
                  const a = {
                    type: value,
                    value: item.id,
                    label: item.agentName,
                    leaf: true,
                  };
                  list.push(a);
                });

                resolve(list);
              } else {
                resolve([]);
              }
            });
        } else if (value == 2) {
          api.channelAgent
            .PARTTIMEBIGBAG_LIST({ page: 1, pageSize: 1000 })
            .then((res) => {
              if (!res.code && res.data) {
                const list = [];
                res.data.list.forEach((item) => {
                  const a = {
                    type: value,
                    value: item.id,
                    label: item.userName,
                    leaf: true,
                  };
                  list.push(a);
                });

                resolve(list);
              } else {
                resolve([]);
              }
            });
        } else if (value == 3) {
          api.distributors
            .DISTRIBUTORS_LIST({ page: 1, pageSize: 1000 })
            .then((res) => {
              if (!res.code && res.data) {
                const list = [];
                res.data.list.forEach((item) => {
                  const a = {
                    type: value,
                    value: item.id,
                    label: item.distributeName,
                    leaf: true,
                  };
                  list.push(a);
                });

                resolve(list);
              } else {
                resolve([]);
              }
            });
        } else if (value == 4) {
          api.terminal
            .TERMINAL_LIST({ page: 1, pageSize: 1000, statusType: 2 })
            .then((res) => {
              if (!res.code && res.data) {
                const list = [];
                res.data.list.forEach((item) => {
                  const a = {
                    type: value,
                    value: item.id,
                    label: item.terminalName,
                    leaf: true,
                  };
                  list.push(a);
                });

                resolve(list);
              } else {
                resolve([]);
              }
            });
        }
      },
    });

    var data = reactive({
      queryParams: {
        charge: "1", // 1 我负责 2 我下级 3 我部门
        cycle: "1", //
        start: null, //
        end: null, // 非必须
        productId: null, // 产品id
        productLine: null, // 产品线id
        distributeId: null, // 配送商id
        dep: [],
        depId: 0,
        userId: 0,
        agentId: 0,
        terminalId: 0,
      },
      cycleData: crmStore.getters["dictionary/getDictionary"]["cycle"],
      dateTimeRef: null,
      listData: [],
      productList: [],
      distributeList: [],
      visible: false,
      depOptions: [],
      clientOptions: [
        {
          value: "1",
          label: "代理商",
        },
        {
          value: "2",
          label: "兼职",
        },
        {
          value: "3",
          label: "配送商",
        },
        {
          value: "4",
          label: "终端",
        },
      ],
    });

    // 统计周期
    const handlCycle = (val) => {
      data.dateTimeRef.handlRemove();
      data.queryParams.cycle = val;
      handlQueryParams();
    };

    // 时间
    const dateTime = (val) => {
      data.queryParams.start = val.start_time;
      data.queryParams.end = val.end_time;
      handlQueryParams();
    };

    // 获取产品线
    const handlProductLineData = () => {
      api.system.PRODUCTLINE_LIST().then((res) => {
        if (res.code === 0) {
          data.listData = res.data.list;
        }
      });
    };

    // 获取产品
    const handlProductData = async (queryString) => {
      const res = await api.developCustomer.PRODUCTID(queryString);
      if (res.code === 0) {
        data.productList = res.data.list;
      }
    };

    // 获取配送商
    const handlDistributeData = async (queryString) => {
      const res = await api.terminal.PRODUCT_PULLLIST(queryString);
      if (res.code === 0) {
        data.distributeList = res.data.list;
      }
    };

    const handlQueryParams = () => {
      context.emit("change", data.queryParams);
    };

    // 重置
    const handlReset = () => {
      let aaa = {}
      if (props.screenData){
        aaa[props.screenData.name] = data.queryParams[props.screenData.name]
      }

      data.queryParams = {
        charge: "1", // 1 我负责 2 我下级 3 我部门
        cycle: "1", //
        start: null, //
        end: null, // 非必须
        productId: null, // 产品id
        productLine: null, // 产品线id
        distributeId: null, // 配送商id
        ...aaa
      };
      data.dateTimeRef.handlRemove();
      let a = new Date(new Date().getTime() - 24 * 60 * 60 * 1000 * 6);
      let b =
        currentInstance.proxy.dateFormat("yyyy-mm-dd", new Date()) +
        " " +
        "23:59:59";
      let c =
        currentInstance.proxy.dateFormat("yyyy-mm-dd", a) + " " + "00:00:00";
      data.queryParams.start = handlHours(c);
      data.queryParams.end = handlHours(b);
      handlQueryParams();
    };

    const handlHours = (val) => {
      var date = new Date(val);
      var hours = date.getHours() + 8;
      date.setHours(hours);
      const str = date.toISOString().replace(".000Z", "+08:00");
      return str;
    };

    watch(
      () => props.isCycle,
      (newV, oldV) => {
        data.queryParams.cycle = "1";
      }
    );

    watch(
      () => props.screenData,
      (newV, oldV) => {
        if (newV) {
          data.queryParams[newV.name] = newV.value;
        }
      }
    );

    const clientChange = (val) => {
      console.log(val);
      if (val) {
        if (val[0] == 1) {
          data.queryParams.agentId = val[1];
          data.queryParams.distributeId = 0;
          data.queryParams.terminalId = 0;
        } else if (val[0] == 2) {
          data.queryParams.agentId = val[1];
          data.queryParams.distributeId = 0;
          data.queryParams.terminalId = 0;
        } else if (val[0] == 3) {
          data.queryParams.distributeId = val[1];
          data.queryParams.agentId = 0;
          data.queryParams.terminalId = 0;
        } else if (val[0] == 4) {
          data.queryParams.terminalId = val[1];
          data.queryParams.agentId = 0;
          data.queryParams.distributeId = 0;
        }
      }
      handlQueryParams();
    };

    const depChange = (val) => {
      if (val) {
        let list = data.depOptions;
        let dep = {};
        for (let i = 0; i < val.length; i++) {
          const index = list.findIndex((a) => a.id == val[i]);
          if (index != -1) {
            if (i != val.length - 1) {
              list = list[index].children;
            } else {
              dep = list[index];
            }
          }
        }

        if (dep.isUser) {
          data.queryParams.userId = dep.id;
          data.queryParams.depId = 0;
        } else {
          data.queryParams.userId = 0;
          data.queryParams.depId = dep.id;
        }

        handlQueryParams();
      }
    };

    const getDepUser = () => {
      api.terminal.DEPARTMENT_LIST().then((res) => {
        if (res.code === 0) {
          console.log(res.data);
          dealDep(res.data);
          data.depOptions = res.data;
        }
      });
    };

    const dealDep = (list) => {
      for (let i = 0; i < list.length; i++) {
        const item = list[i];
        if (item.children && item.children.length) {
          dealDep(item.children);
        }
        if (item.users) {
          item.users.forEach((user) => {
            const a = { ...user };
            a.isUser = true;
            a.deptName = a.realName;
            if (!item.children) {
              item.children = [];
            }
            item.children.push(a);
          });
        }
      }
    };

    const handlQueryType = () => {
      if (route.query.type) {
        switch (route.query.type) {
          case "1":
            data.queryParams.cycle = "1";
            break;
          case "2":
            data.queryParams.cycle = "3";
            break;
          case "3":
            data.queryParams.cycle = "3";
            break;
          case "4":
            data.queryParams.cycle = "3";
            break;
        }
      }
    };

    onMounted(() => {
      handlProductLineData();
      getDepUser();
      handlQueryType();
    });

    return {
      ...toRefs(data),
      handlCycle,
      dateTime,
      handlQueryParams,
      handlDistributeData,
      handlProductData,
      handlProductLineData,
      handlReset,
      depChange,
      clientChange,
      propsOption,
      handlQueryType,
      handlHours,
    };
  },
};
</script>

<style scoped>
/* @import url(); 引入css类 */
</style>
